<template>
  <section class="container relative">
    <el-image
      style="width: 100vw; height: calc(100vh - 74px); vertical-align: middle"
      :src="require('@/assets/images/car.png')"
      fit="cover"
    >
      <template #error>
        <icon-ep-picture class="w-full h-full text-gray-300" />
      </template>
    </el-image>
    <aside
      class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 bg-[rgba(255,255,255,.8)] px-6 pb-6 rounded"
    >
      <h1 class="text-xl text-center text-primary my-6">用户登录</h1>
      <el-form :model="loginForm" :rules="loginRules" ref="loginForm" @keyup.enter.native="submitForm">
        <el-form-item label="用户名" prop="username">
          <el-input placeholder="请输入用户名" v-model="loginForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input placeholder="请输入密码" v-model="loginForm.password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">登陆</el-button> &nbsp;&nbsp;
          <el-link type="info" @click="$router.push('/register')">若没有账号，请点击这里注册</el-link>
        </el-form-item>
      </el-form>
    </aside>
  </section>
</template>

<script>
  export default {
    name: 'Login',
    data() {
      return {
        // 登陆表单数据
        loginForm: {
          username: '',
          password: '',
        },
        // 登录表单校验规则
        loginRules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 11, message: '长度在 3 到 11 个字符', trigger: 'blur' },
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            {
              min: 6,
              message: '长度不能小于6',
              trigger: 'blur',
            },
          ],
        },
      }
    },
    methods: {
      ...mapActions('user', ['reqLogin']),
      // 提交表单
      submitForm() {
        this.$refs.loginForm.validate(async valid => {
          if (valid) {
            try {
              await this.reqLogin(this.loginForm)
            } catch (error) {
              this.$refs.loginForm.resetFields()
              return this.$message.error('登录失败，请重新填写用户名和密码')
            }
            this.redirect ? this.$router.push(this.redirect) : this.$router.push('/home')
          } else {
            return this.$message.error('请按照要求正确输入！')
          }
        })
      },
    },
    computed: {
      redirect() {
        return this.$route.query.redirect || ''
      },
    },
  }
</script>
